package com.cheetah.start.system.admin.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cheetah.start.common.annotation.ApiCount;
import com.cheetah.start.common.annotation.Log;
import com.cheetah.start.common.base.result.Result;
import com.cheetah.start.common.base.result.ResultController;
import com.cheetah.start.common.base.result.ResultTable;
import com.cheetah.start.common.base.validation.Add;
import com.cheetah.start.common.base.validation.Edit;
import com.cheetah.start.common.enums.BusinessTypeEnum;
import com.cheetah.start.common.enums.LogTypeEnum;
import com.cheetah.start.common.query.PageQuery;
import com.cheetah.start.common.utils.MySecurityUtil;
import com.cheetah.start.system.admin.domain.SysAdmin;
import com.cheetah.start.system.admin.service.SysAdminService;
import com.cheetah.start.system.role.service.SysRoleAdminService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.util.List;

/**
 * @author Feel
 * @date 2021/10/21 10:07
 * @Description:
 */
@Api(tags = {"后台用户crud"})
@Slf4j
@ApiCount
@CrossOrigin
@Validated
@RestController
@RequestMapping("/admin")
public class SysBaseAdminController extends ResultController {
    @Autowired
    private SysAdminService sysAdminService;
    @Autowired
    private SysRoleAdminService sysRoleAdminService;

    /**
     * 列表
     *
     * @param pageQuery 页面查询
     * @param admin     管理
     * @return {@link ResultTable}
     */
    @SaCheckPermission(value = "sys:admin:data",orRole = "admin")
    @ApiOperation("用户列表")
    @GetMapping("/list")
    public ResultTable list(PageQuery pageQuery, SysAdmin admin) {
        Page<SysAdmin> page = new Page<>(pageQuery.getPage(), pageQuery.getLimit());
        QueryWrapper<SysAdmin> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("create_time");
        sysAdminService.page(page, wrapper);
        List<SysAdmin> records = page.getRecords();
        sysAdminService.setRoleIds(records);
        return pageTable(records, page.getTotal());
    }

    /**
     * 添加
     *
     * @param sysAdmin 系统管理员
     * @return {@link Result}
     */
    @SaCheckPermission(value = "sys:admin:add",orRole = "admin")
    @ApiOperation("用户添加")
    @Log(title = "用户", describe = "添加", type = BusinessTypeEnum.ADD, logType = LogTypeEnum.OPERATE)
    @PostMapping("/save")
    public Result add(@Validated(value = Add.class) SysAdmin sysAdmin) {
        if (sysAdminService.isRepeat(sysAdmin)) {
            return failure("账户名不能重复");
        }
        sysAdmin.setPassword(MySecurityUtil.encode(sysAdmin.getPassword()));
        boolean save = sysAdminService.saveWithRoleIds(sysAdmin);
        return decide(save, BusinessTypeEnum.ADD);
    }

    /**
     * 更新
     *
     * @param sysAdmin 系统管理员
     * @return {@link Result}
     */
    @ApiOperation("用户编辑")
    @SaCheckPermission(value = "sys:admin:edit",orRole = "admin")
    @Log(title = "用户", describe = "编辑", type = BusinessTypeEnum.EDIT, logType = LogTypeEnum.OPERATE)
    @PostMapping("/update")
    public Result update(@Validated(value = Edit.class) SysAdmin sysAdmin) {
        SysAdmin byId = sysAdminService.getById(sysAdmin.getAdminId());
        if ("admin".equals(byId.getName()) && !"admin".equals(sysAdmin.getName())) {
            if (StrUtil.isBlank(sysAdmin.getRoleIds())){
                return failure("超级管理员角色不能为空");
            }
            return failure("不能修改超级管理员账户名");
        }
        if (sysAdminService.isRepeat(sysAdmin)) {
            return failure("账户名不能重复");
        }
        boolean b = sysAdminService.updateByIdWithRole(sysAdmin);
        return decide(b, BusinessTypeEnum.EDIT);
    }

    /**
     * 删除
     *
     * @param adminId 管理员id
     * @return {@link Result}
     */
    @SaCheckPermission(value = "sys:admin:delete",orRole = "admin")
    @ApiOperation("删除")
    @Log(title = "用户", describe = "删除", type = BusinessTypeEnum.REMOVE, logType = LogTypeEnum.OPERATE)
    @PostMapping("/delete")
    public Result delete(@NotNull(message = "ID不能为空") Integer adminId) {
        SysAdmin byId = sysAdminService.getById(adminId);
        if ("admin".equals(byId.getName())) {
            return failure("超级管理员不能删除");
        }
        boolean b = sysAdminService.removeById(adminId);
        sysRoleAdminService.removeByAdminId(adminId);
        return decide(b, BusinessTypeEnum.REMOVE);
    }
}
